package com.ruoyi.tenant.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.datasource.DynamicDataSource;
import com.ruoyi.tenant.domain.SysTenant;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class AddDataSourceUtil {

    public static void addDataSource(SysTenant sysTenant){
        DynamicDataSource dynamicDataSource = SpringUtils.getBean("dynamicDataSource");
        Map<Object, javax.sql.DataSource> resolvedDataSourcesMap = dynamicDataSource.getResolvedDataSources();
        Set<Object> dynamicDataSourceSet = resolvedDataSourcesMap.keySet();
        //若数据连接池没有则添加
        if (!dynamicDataSourceSet.contains(sysTenant.getTenantid())) {
            //获取现在已有的数据源
            Map<Object, Object> map = new ConcurrentHashMap<>();
            for (Object key : resolvedDataSourcesMap.keySet()) {
                map.put(key, resolvedDataSourcesMap.get(key));
            }
            buildDataSources(map, sysTenant.getTenantid(), sysTenant);
            dynamicDataSource.setTargetDataSources(map);
            dynamicDataSource.afterPropertiesSet();
        }
    }


    private static void buildDataSources(Map<Object, Object> map, String tenantid, SysTenant sysTenant) {
        //TODO 远程获取数据源状态,如果是 启用状态则添加 否则不添加 如果已停用就删除
        Properties properties = new Properties();
        properties.put("url", sysTenant.getUrl());
        properties.put("username", sysTenant.getUsername());
        properties.put("password", sysTenant.getPassword());
        properties.put("driverClassName", "com.mysql.cj.jdbc.Driver");
        properties.put("initialSize","5");
        properties.put("minIdle", "10");
        properties.put("maxActive", "20");
        properties.put("maxWait", "60000");
        properties.put("connectTimeout", "30000");
        properties.put("socketTimeout","60000");
        properties.put("timeBetweenEvictionRunsMillis", "60000");
        properties.put("minEvictableIdleTimeMillis", "300000");
        properties.put("validationQuery", "SELECT 1 FROM DUAL");
        properties.put("testWhileIdle","true");
        properties.put("testOnBorrow", "false");
        properties.put("testOnReturn", "false");
        properties.put("filters","com.alibaba.druid.filter.stat.StatFilter");

        javax.sql.DataSource dataSource = null;
        try {
            DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
            druidDataSource.setConnectionErrorRetryAttempts(0);// 失败后重连的次数
            druidDataSource.setBreakAfterAcquireFailure(true);//请求失败之后中断
            dataSource = druidDataSource;
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put(tenantid, dataSource);
    }
}
